// Author: wsfuyibing <682805@qq.com>
// Date: 2025-04-28

package middlewares

import (
    "context"
    "gitee.com/go-libs/log"
    "gitee.com/go-libs/result"
    "gitee.com/go-wares/framework-iris/framework/src/middlewares"
    "github.com/kataras/iris/v12"
    "server/app/errs"
    "server/app/lib/authorizer"
)

// AuthorizerMiddleware
// 用户鉴权.
//
// @Name("authorizer")
func AuthorizerMiddleware(i iris.Context) {
    var (
        auth           = authorizer.New()
        authentication *authorizer.Authentication
        ctx            context.Context
        err            error
        token          = auth.GetHeaderToken(i)
    )

    // 1. 继承链路.
    if span, ok := i.Values().Get(middlewares.TracingSpan).(log.Span); ok {
        ctx = span.GetContext()
    } else {
        ctx = i.Request().Context()
    }

    // 2. 获取令牌.
    //    取请求头的 Authorization 的值.
    if token == "" {
        log.Infofc(ctx, `[middleware=authorize] authorization token not specified by header`)
        _ = i.JSON(result.New().WithError(errs.ErrUserUnauthorized))
        return
    }

    // 3. 校验令牌.
    if authentication, err = auth.Verify(token); err != nil {
        log.Infofc(ctx, `[middleware=authorize] authorization token verify failed: error="%v"`, err)
        _ = i.JSON(result.New().WithError(errs.ErrUserUnauthorized))
        return
    }

    // 4. 校验通过.
    log.Infofc(ctx, `[middleware=authorize] authorization token verified: token="%s"`, token)
    auth.Set(i, authentication)
    defer auth.Unset(i)
    i.Next()
}
